/*
Copyright (c) 2002 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 */
package redora.util;

import org.jetbrains.annotations.NotNull;
import redora.exceptions.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.util.logging.Logger;

import static java.util.logging.Level.FINE;
import static java.util.logging.Level.INFO;

/**
 * Checks a string character for character and checks if it is valid for JSON.
 * Escapes it if not.
 *
 * @author Nanjing RedOrange (www.red-orange.cn)
 */
public class JSONTokener {

    static final transient Logger l = Logger.getLogger("json.JSONTokener");
    int character = 1;
    boolean eof = false;
    int index = 0;
    StringBuilder line = new StringBuilder();
    char previous = 0;
    final Reader reader;

    /**
     * Construct a JSONTokener from a reader.
     *
     * @param reader     A reader.
     */
    public JSONTokener(@NotNull Reader reader) {
        this.reader = reader.markSupported()
                ? reader : new BufferedReader(reader);
    }

    /**
     * Construct a JSONTokener from a string.
     *
     * @param s     A source string.
     */
    public JSONTokener(@NotNull String s) {
        this(new StringReader(s));
        l.log(FINE, "Tokening from string {0}", s);
    }

    /**
     * Get the next character in the source string.
     *
     * @return The next character, or 0 if past the end of the source string.
     */
    char next() throws JSONException {
        int c;
        try {
            c = this.reader.read();
        } catch (IOException ex) {
            throw new JSONException(ex);
        }

        if (c <= 0) { // End of stream
            this.eof = true;
        } else {
            this.index++;
            if (l.isLoggable(INFO)) {
                line.append((char) c);
            }
        }
        if (this.previous == '\r' || c == '\n') {
            this.line = new StringBuilder();
            this.character = c == '\n' ? 0 : 1;
        } else {
            this.character++;
        }
        this.previous = (char) c;
        return this.previous;
    }

    /**
     * Get the next n characters.
     *
     * @param n     The number of characters to take.
     * @return      A string of n characters.
     * @throws JSONException
     *   Substring bounds error if there are not
     *   n characters remaining in the source string.
     */
    char[] next(int n) throws JSONException {
        if (n <= 0) {
            throw new IllegalArgumentException("The n parameter should be larger then 0 (" + n + ")");
        }

        char[] buffer = new char[n];
        for (int pos = 0; pos < n; pos++) {
            buffer[pos] = next();
            if (eof) {
                throw syntaxError("Substring bounds error");
            }
        }
        return buffer;
    }

    public void stream(@NotNull PrintWriter out) throws JSONException {
        char c = next();
        while (!eof) {
            switch (c) {
                case '\"':
                    out.write("\\\"");
                    break;
                case '\n':
                    out.write("\\n");
                    break;
                case '\r':
                    out.write("\\r");
                    break;
                //throw syntaxError("Unterminated string");
                case '\\':
                    out.write("\\\\");
                    break;
                default:
                    out.write(c);
                    break;
            }
            c = next();
        }
    }

    /**
     * Make a JSONException to signal a syntax error.
     *
     * @param message The error message.
     * @return  A JSONException object, suitable for throwing
     */
    JSONException syntaxError(String message) {
        return new JSONException(message + toString());
    }

    /**
     * Make a printable string of this JSONTokener.
     *
     * @return " at {index} [character {character} line {line}]"
     */
    @Override
    public String toString() {
        return " at " + index + " [character " + this.character + " in line: '" + this.line + "']";
    }
}
